using Microsoft.Maui.Controls;
using System;

#if WINDOWS
using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Input;
using Windows.System;
using Windows.UI.Core;
#endif

namespace MauiApp.Views
{
    [QueryProperty(nameof(FilePath), nameof(FilePath))]
    public partial class ImageViewerPage : ContentPage
    {
        public string FilePath
        {
            get => (string)GetValue(FilePathProperty);
            set => SetValue(FilePathProperty, value);
        }

        public static readonly BindableProperty FilePathProperty = BindableProperty.Create(
            nameof(FilePath), typeof(string), typeof(ImageViewerPage), default(string), propertyChanged: OnFilePathChanged);

        public ImageViewerPage()
        {
            InitializeComponent();

#if WINDOWS
            Loaded += (_, __) =>
            {
                if (Handler?.PlatformView is UIElement element)
                {
                    element.PointerWheelChanged += OnPointerWheelChanged;
                }
            };
#endif
        }

#if WINDOWS
        private void OnPointerWheelChanged(object sender, PointerRoutedEventArgs e)
        {
            // Ctrl + 滚轮缩放（Windows 上由 XAML 层处理，Android 使用原生 Handler）
            var ctrlDown = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
            if (ctrlDown)
            {
                var props = e.GetCurrentPoint((UIElement)sender).Properties;
                var factor = props.MouseWheelDelta > 0 ? 1.1 : 0.9;
                PreviewImage.Scale *= factor;
                e.Handled = true;
            }
        }
#endif

        private static void OnFilePathChanged(BindableObject bindable, object oldValue, object newValue)
        {
            if (bindable is ImageViewerPage page && newValue is string path && !string.IsNullOrWhiteSpace(path))
            {
                page.PreviewImage.Source = ImageSource.FromFile(path);
            }
        }

        private async void OnBackClicked(object? sender, EventArgs e)
        {
            if (Shell.Current?.Navigation?.NavigationStack?.Count > 1)
            {
                await Shell.Current.Navigation.PopAsync(animated: true);
            }
            else
            {
                await Shell.Current.GoToAsync("//MainPages/MainPage");
            }
        }
    }
}
